package com.lemon.smartsafetynew.ui.activity.record;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerNewTClickListener;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafetynew.entity.FileInfo;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.me.MeCompanyVo;
import com.lemon.smartsafetynew.entity.record.CompanyBaseVo;
import com.lemon.smartsafetynew.entity.record.CompanyPeopleVo;
import com.lemon.smartsafetynew.net.services.RecordServices;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafetynew.ui.adapter.record.CompanyPeopleAdapter;
import com.lemon.smartsafetynew.ui.adapter.record.FilesAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 一企一档基本信息
 * Created by JiangAn on 2018/5/22.
 */

public class RecordBaseInfoActivity extends SwipeBackActivity
        implements RecyclerTClickListener<FileInfo>, RecyclerNewTClickListener<CompanyPeopleVo> {

    @Bind(R.id.iv_return)
    ImageView ivReturn;
    @Bind(R.id.tv_item_company_name)
    TextView tvItemCompanyName;
    @Bind(R.id.tv_item_company_code)
    TextView tvItemCompanyCode;
    @Bind(R.id.tv_item_company_address)
    TextView tvItemCompanyAddress;
    @Bind(R.id.tv_item_company_real_address)
    TextView tvItemCompanyRealAddress;
    @Bind(R.id.tv_item_company_execl_address)
    TextView tvItemCompanyExeclAddress;
    @Bind(R.id.tv_big_hidden_level)
    TextView tvBigHiddenLevel;
    @Bind(R.id.tv_safe_monitor_level)
    TextView tvSafeMonitorLevel;
    @Bind(R.id.expand)
    TextView expand;
    @Bind(R.id.tv_monitor_type)
    TextView tvMonitorType;
    @Bind(R.id.tv_economic_type)
    TextView tvEconomicType;
    @Bind(R.id.tv_industry_type)
    TextView tvIndustryType;
    @Bind(R.id.tv_legal_people)
    TextView tvLegalPeople;
    @Bind(R.id.tv_address_origination)
    TextView tvAddressOrigination;
    @Bind(R.id.tv_formal_level)
    TextView tvFormalLevel;
    @Bind(R.id.tv_company_status)
    TextView tvCompanyStatus;
    @Bind(R.id.tv_liscense_type)
    TextView tvLiscenseType;
    @Bind(R.id.tv_origination_code)
    TextView tvOriginationCode;
    @Bind(R.id.tv_register_money)
    TextView tvRegisterMoney;
    @Bind(R.id.tv_practitioners)
    TextView tvPractitioners;
    @Bind(R.id.ll_expand)
    RelativeLayout llExpand;
    @Bind(R.id.recyclePeople)
    RecyclerView recyclePeople;
    @Bind(R.id.tv_special_people_num)
    TextView tvSpecialPeopleNum;
    @Bind(R.id.tv_full_time_safe_manager_people)
    TextView tvFullTimeSafeManagerPeople;
    @Bind(R.id.tv_part_time_safe_manager_people)
    TextView tvPartTimeSafeManagerPeople;
    @Bind(R.id.tv_full_time_emergency_people)
    TextView tvFullTimeEmergencyPeople;
    @Bind(R.id.tv_register_safe_manager)
    TextView tvRegisterSafeManager;
    @Bind(R.id.tv_safe_grid_people)
    TextView tvSafeGridPeople;
    @Bind(R.id.tv_service_date)
    TextView tvServiceDate;
    @Bind(R.id.tv_business_scope)
    TextView tvBusinessScope;
    @Bind(R.id.tv_file_none)
    TextView tvFileNone;
    @Bind(R.id.ry_files)
    RecyclerView ryFiles;
    @Bind(R.id.tv_company_belong_to)
    TextView tvCompanyBelongTo;
    @Bind(R.id.origination_code)
    TextView originationCode;
    @Bind(R.id.register_money)
    TextView registerMoney;
    @Bind(R.id.practitioners)
    TextView practitioners;
    @Bind(R.id.special_people_num)
    TextView specialPeopleNum;
    @Bind(R.id.full_time_safe_manager_people)
    TextView fullTimeSafeManagerPeople;
    @Bind(R.id.part_time_safe_manager_people)
    TextView partTimeSafeManagerPeople;
    @Bind(R.id.full_time_emergency_people)
    TextView fullTimeEmergencyPeople;
    @Bind(R.id.register_safe_manager)
    TextView registerSafeManager;
    @Bind(R.id.safe_grid_people)
    TextView safeGridPeople;
    @Bind(R.id.service_date)
    TextView serviceDate;
    @Bind(R.id.business_scope)
    TextView businessScope;


    private Boolean isExpand = true; //是否展开
    private static MeCompanyVo companyVo;

    private CompanyPeopleAdapter adapter;
    private List<CompanyPeopleVo> mList;


    @Override
    protected void initTitle() {
        this.setBarTitle("基本信息");
    }

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey(KeyConstants.KEY_COMPANY_VO)) {
                companyVo = (MeCompanyVo) bundle.getSerializable(KeyConstants.KEY_COMPANY_VO);
            }
        }
    }

    @Override
    protected void initViews() {
        super.initViews();

        ivReturn.setVisibility(View.INVISIBLE);

        mList = new ArrayList<>();
        adapter = new CompanyPeopleAdapter(mList, this, false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclePeople.setNestedScrollingEnabled(false);
        recyclePeople.setLayoutManager(layoutManager);
        recyclePeople.setAdapter(adapter);

        getCompanyBaseInfo(); //获取企业基本信息
        getData(); //获取用户列表数据
    }


    /**
     * 获取用户列表数据
     */
    private void getData() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("company_id", companyVo.getCompany_id());
        RecordServices.init().getCompanyPeopleInfo(params);
    }

    /**
     * 获取企业基本信息
     */
    private void getCompanyBaseInfo() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("companyId", companyVo.getCompany_id());
        RecordServices
                .init()
                .getCompanyInfo(params);
    }

    @Override
    protected void initListener() {
        super.initListener();
        expand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isExpand) {
                    isExpand = false;
                    expand.setText("收起");
                    llExpand.setVisibility(View.VISIBLE);
                } else {
                    isExpand = true;
                    expand.setText("展开");
                    llExpand.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(RecordBaseInfoActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_record_base_info;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_RECORD_BASE_INFO.equals(event.getTag())) {                                     //获取企业基本信息
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    if (event.getObj() instanceof CompanyBaseVo) {
                        CompanyBaseVo companyBaseVo = (CompanyBaseVo) event.getObj();
                        initData(companyBaseVo);
                    }
                }
            }
        } else if (KeyConstants.URL_GET_RECORD_COMPANY_PEOPLE_INFO.equals(event.getTag())) {                    //获取人员信息
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    if (adapter != null) {
                        mList.clear();
                        adapter.notifyDataSetChanged();
                        adapter.addItems((List<CompanyPeopleVo>) event.getObj());
                    }

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });

                }
            }

        }
    }

    //显示数据
    private void initData(CompanyBaseVo companyBaseVo) {
        tvItemCompanyName.setText(CommonUtil.avoidNullString(companyBaseVo.getCompany_name()));
        tvItemCompanyCode.setText(CommonUtil.avoidNullString(companyBaseVo.getCompany_code()));
        tvItemCompanyAddress.setText(CommonUtil.avoidNullString(companyBaseVo.getRegister_address()));
        tvItemCompanyRealAddress.setText(CommonUtil.avoidNullString(companyBaseVo.getAddress()));
        //暂时为空
        tvItemCompanyExeclAddress.setText(CommonUtil.avoidNullString(companyBaseVo.getPlaceInfo()));

        tvBigHiddenLevel.setText(CommonUtil.avoidNullString(companyBaseVo.getDangerSourceLevel()));
        tvSafeMonitorLevel.setText(CommonUtil.avoidNullString(companyBaseVo.getStandardLevelId()));
        tvMonitorType.setText(CommonUtil.avoidNullString(companyBaseVo.getIndustryCategory()));
        tvEconomicType.setText(CommonUtil.avoidNullString(companyBaseVo.getEconomicType()));

        tvIndustryType.setText(CommonUtil.avoidNullString(companyBaseVo.getRegulatoryClassify()));

        tvLegalPeople.setText(CommonUtil.avoidNullString(companyBaseVo.getLegal_person()));

        tvAddressOrigination.setText(CommonUtil.avoidNullString(companyBaseVo.getSafety_agencies()));

        tvFormalLevel.setText(CommonUtil.avoidNullString(companyBaseVo.getReachLevel()));

        tvCompanyStatus.setText(CommonUtil.avoidNullString(companyBaseVo.getCompanyState()));

        tvLiscenseType.setText(CommonUtil.avoidNullString(companyBaseVo.getBusinessLicense()));

        tvOriginationCode.setText(CommonUtil.avoidNullString(companyBaseVo.getInstitution_code()));
        tvRegisterMoney.setText(CommonUtil.avoidNullString(companyBaseVo.getRegistered_fund()));
        if (!TextUtils.isEmpty(companyBaseVo.getNumber_of_practitioner())) {
            tvPractitioners.setText(CommonUtil.avoidNullString(companyBaseVo.getNumber_of_practitioner()));
        }
        tvSpecialPeopleNum.setText(CommonUtil.avoidNullString(companyBaseVo.getNumber_of_special()));
        tvFullTimeSafeManagerPeople.setText(CommonUtil.avoidNullString(companyBaseVo.getFull_time_number()));
        tvPartTimeSafeManagerPeople.setText(CommonUtil.avoidNullString(companyBaseVo.getPart_time_number()));
        tvCompanyBelongTo.setText(CommonUtil.avoidNullString(companyBaseVo.getAdministrativeRelation()));
        tvFullTimeEmergencyPeople.setText(CommonUtil.avoidNullString(companyBaseVo.getFull_time_manage()));
        tvRegisterSafeManager.setText(CommonUtil.avoidNullString(companyBaseVo.getCertified_safety_engineer()));
        tvSafeGridPeople.setText(CommonUtil.avoidNullString(companyBaseVo.getSafety_person()) + "  " + CommonUtil.avoidNullString(companyBaseVo.getSafety_person_phone()));
        if ((companyBaseVo.getEffective_end_date() == null) && (companyBaseVo.getEffective_start_date() == null)) {
            tvServiceDate.setText("");
        } else {
            tvServiceDate.setText(CommonUtil.secondToTimeStr(companyBaseVo.getEffective_start_date(), DateTypeEnum.DAY)
                    + " 至 " + CommonUtil.secondToTimeStr(companyBaseVo.getEffective_end_date(), DateTypeEnum.DAY));
        }
        tvBusinessScope.setText(CommonUtil.avoidNullString(companyBaseVo.getMajor_product()));
        if (!TextUtils.isEmpty(companyBaseVo.getLevel_file_url())) {
            tvFileNone.setVisibility(View.GONE);
            ryFiles.setVisibility(View.VISIBLE);
            List<String> list = Arrays.asList(companyBaseVo.getLevel_file_url().split(","));//根据逗号分隔转化为list
            List<FileInfo> fileList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                FileInfo fileinfo = new FileInfo();
                fileinfo.setName("附件"+(i+1));
                fileinfo.setUrl(HttpUtils.formatFilesUrl(list.get(i)));
                fileList.add(fileinfo);
            }
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(RecordBaseInfoActivity.this);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            ryFiles.setLayoutManager(linearLayoutManager);
            ryFiles.setNestedScrollingEnabled(false);
            FilesAdapter mAdapter = new FilesAdapter(fileList, this);
            ryFiles.setAdapter(mAdapter);
        } else {
            tvFileNone.setVisibility(View.VISIBLE);
            ryFiles.setVisibility(View.GONE);
        }
    }

    @Override
    public void onNewItemClick(CompanyPeopleVo data, int position) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + data.getMobile()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onItemClick(FileInfo data, int position) {
        downloadAndShowFile(data.getUrl(), data.getName(), this, "基本信息");
    }

}
